<?php
	/**
	 * 模板管理类
	 * detail description
	 * @todo
	 * @author swingcoder <swingcoder@msn.com>
	 * @version 0.1
	 * @copyright Copyright (c) 2009, swingcoder.com
	 */

	class tpl
	{
		var $database = null;
		//禁止存在下列危险函数的模板文件上传
		var $disabled_functions = '"apache_child_terminate,apache_setenv,define_syslog_variables,escapeshellarg,escapeshellcmd,eval,exec,fp,fput,ftp_connect,ftp_exec,ftp_get,ftp_login,ftp_nb_fput,ftp_put,ftp_raw,ftp_rawlist,highlight_file,ini_alter,ini_get_all,ini_restore,inject_code,mysql_pconnect,openlog,passthru,php_uname,phpAds_remoteInfo,phpAds_XmlRpc,phpAds_xmlrpcDecode,phpAds_xmlrpcEncode,popen,posix_getpwuid,posix_kill,posix_mkfifo,posix_setpgid,posix_setsid,posix_setuid,posix_setuid,posix_uname,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,shell_exec,syslog,system,xmlrpc_entity_decode,copy,delete,file_get_contents,file_put_contents,file,fopen,fputs,fwrite,glob,mkdir,move_uploaded_file,popen,readfile,rename,symlink,touch,umask,unlink,chmod,chown,chgrp,file_exists,is_file,link,mysql_connect,dl';

		function tpl()
		{
			$this->database = load( 'database' );
		}


		//返回分页模板列表数据
		function all( $data )
		{
			$size = isset( $data['size'] ) && preg_match( '!^\d+$!', $data['size'] ) ? $data['size'] : 12;
			$page = isset( $data['page'] ) && preg_match( '!^\d+$!', $data['page'] ) ? $data['page'] : 1;
			$order = isset( $data['order'] ) ? $data['order'] : 'cate_id desc';
			$type = isset( $data['type'] ) ? $data['type'] : '';
			$cate_id = isset( $data['cate_id'] ) ? $data['cate_id'] : '';
			$where = ' where status=0 ';
			if ( $type != '' )
			{
				$where .= ' and type=' . $type;
			}
			if ( $cate_id != '' )
			{
				$where .= ' and cate_id=' . $cate_id;
			}
			$count = 'from tpl ' . $where;
			$list = 'select * ' . $count . ' order by ' . $order;
			$result = $this->database->split( $count, $list, $size, $page );

			return $result;
		}


		//获取单条模板的数据
		function get( $data )
		{
			$result = array();
			$where = ' where status=0 ';
			if ( isset( $data['id'] ) && preg_match( '!^\d+$!', $data['id'] ) )
			{
				$where .= ' and id=' . $data['id'];
			}

			if ( isset( $data['cate_id'] ) && preg_match( '!^\d+$!', $data['cate_id'] ) )
			{
				$where .= ' and cate_id=' . $data['cate_id'];
			}

			if ( isset( $data['type'] ) && preg_match( '!^\d+$!', $data['type'] ) )
			{
				$where .= ' and type=' . $data['type'];
			}

			$result = $this->database->unique( 'select * from tpl ' . $where );

			return $result;
		}


		//修改模板
		function set( $data )
		{
			$result = array( 'success' => false, 'message' => array() );
			$validation = load( 'validation' );
			$field = array();

			$field['id']['kind'] = '';
			$field['id']['type'] = 'num';
			$field['id']['min'] = '1';
			$field['id']['max'] = '8';
			$field['id']['info'] = '请传递ID';

			$field['htmlsrc']['kind'] = '';
			$field['htmlsrc']['type'] = 'text';
			$field['htmlsrc']['min'] = '1';
			$field['htmlsrc']['max'] = '999999999';
			$field['htmlsrc']['info'] = '请传递模板内容';

			$check = $validation->validate( $field, $data );

			if ( count( $check ) == 0 )
			{
				$data['htmlsrc'] = preg_replace( array( '/require_once/i', '/include_once/i' ), array( 'require' ,'include' ), $data['htmlsrc'] );

				//检查是否存在危险函数
				$disabled_functions = explode( ',', $this->disabled_functions );
				$len = count( $disabled_functions );
				for( $i=0; $i<$len; $i++ )
				{
					preg_match( '/' . $disabled_functions[$i] . ' *\(/i' , $data['htmlsrc'], $matches );
					if ( count( $matches ) > 0 )
					{
						$result['message'][] = '模板中存在非法函数。' . $disabled_functions[$i];
						return $result;
					}
				}

				$tmp = $this->get( $data );
				$f = config( 'dir.tpl.www' ) . $tmp['path'];
				if ( is_file( $f ) && is_writable( $f ) && file_put_contents( $f, $data['htmlsrc']) )
				{
					$result['success'] = true;
					$result['data']['id'] = $data['id'];
				}
				else
				{
					$result['message'][] = '执行修改失败' . $f;
				}
			}
			else
			{
				$result['message'] = $check;
			}

			return $result;
		}


		//添加新的模板
		function add( $data )
		{
			$result = array( 'success' => false, 'message' => array() );
			$validation = load( 'validation' );
			$field = array();

			$field['cate_id']['kind'] = '';
			$field['cate_id']['type'] = 'num';
			$field['cate_id']['min'] = '1';
			$field['cate_id']['max'] = '8';
			$field['cate_id']['info'] = '请传递栏目ID';

			$field['type']['kind'] = '';
			$field['type']['type'] = 'num';
			$field['type']['min'] = '1';
			$field['type']['max'] = '2';
			$field['type']['info'] = '请传递类型id';

			$field['up_tpl_way']['kind'] = '';
			$field['up_tpl_way']['type'] = 'num';
			$field['up_tpl_way']['min'] = '1';
			$field['up_tpl_way']['max'] = '2';
			$field['up_tpl_way']['info'] = '请选择上传模板方式';

			$check = $validation->validate( $field, $data );

			if ( count( $check ) == 0 )
			{

				if ( $this->is_unique( $data['cate_id'], $data['type'] ) )
				{
					//获取栏目英文名,以创建分级目录
					$cate = load( 'biz.cate' );
					$cate_dir = $cate->getdir( $data['cate_id'] );

					if ( $data['up_tpl_way'] == 1 )	 //本地上传
					{
						//处理文件上传
						$config = load( 'biz.argument' );
						$dir_root = config( 'dir.root' );
						$templateurl = $dir_root . $config->value( 'templateurl' );
						$templateurl = str_replace( '//', '/', $templateurl );
						$FILE_NAME_STYLE = 'datetime';
						if ( isset( $cate_dir['dir'] ) && $cate_dir['dir'] != '' && $data['cate_id'] != 0 )
						{
							$templateurl .= $cate_dir['dir'];
						}
						if ( $data['cate_id'] == 0 )
						{
							if ( $data['type'] == 4 )
							{
								$FILE_NAME_STYLE = 'header.htm';
							}
							else if ( $data['type'] == 5 )
							{
								$FILE_NAME_STYLE = 'footer.htm';
							}
							else if ( $data['type'] == 6 )
							{
								$FILE_NAME_STYLE = 'home.htm';
							}
							else
							{
								$FILE_NAME_STYLE = '';	//不会修改文件名
							}
						}

						$upload = load( 'upload' );
						$upload_config = array( 'DEST_DIR' => $templateurl, 'FILE_TYPE' => 'htm,html',  'MUST_UPLOAD_FILE_INDEX' => 0 );
						$upload->init_cfg( array( 'htmlfile' =>  $upload_config ) );
						$upfile = $upload->do_upload();

						if ( isset( $upfile['htmlfile'] ) && count( $upfile ) > 0 && is_file( $upfile['htmlfile'][0] ) )
						{
							$tmp = file_get_contents( $upfile['htmlfile'][0] );
							$tmp = preg_replace( array( '/require_once/i', '/include_once/i' ), array( 'require' ,'include' ), $tmp );

							//检查是否存在危险函数
							$disabled_functions = explode( ',', $this->disabled_functions );
							$len = count( $disabled_functions );
							for( $i=0; $i<$len; $i++ )
							{
								preg_match( '/' . $disabled_functions[$i] . ' *\(/i' , $tmp, $matches );
								if ( count( $matches ) > 0 )
								{
									$result['message'][] = '模板中存在非法函数。' . $disabled_functions[$i];
									return $result;
								}
							}

							file_put_contents( $upfile[0], $tmp, LOCK_EX );

							$data['path'] = substr( $upfile['htmlfile'][0], strlen( $dir_root ) - 1 );
						}
					}
					else	//引用别的栏目模板
					{
						if ( intval( $data['src_cate_id'] ) <= 0 )
						{
							$result['message'][] = '请选择模板来源栏目';
							return $result;
						}
						else
						{
							$tmp = $this->get( array( 'cate_id' => $data['src_cate_id'], 'type' => $data['type'] ) );
							if ( isset( $tmp['path'] ) )
							{
								$data['path'] = $tmp['path'];
								$data['refer_tpl_id'] = $tmp['id'];
							}
							else
							{
								$result['message'][] = '来源栏目模板不存在';
								return $result;
							}
						}
					}

					unset( $data['up_tpl_way'] );
					unset( $data['src_cate_id'] );

					$this->database->start();
					$id = $this->database->add( 'tpl', $data );

					if ( preg_match( '!^\d+$!', $id ) && $this->database->end() )
					{
						$result['success'] = true;
						$result['data']['id'] = $id;
					}
					else
					{
						$result['message'][] = '执行创建失败';
					}
				}
				else
				{
					$result['message'][] = '该栏目下存在同类型文件，请编辑或删除原模板文件。';
				}
			}
			else
			{
				$result['message'] = $check;
			}

			return $result;
		}


		//删除模板
		function del( $data )
		{
			$result = array();
			if ( isset( $data['id'] ) && preg_match( '!^\d+$!', $data['id'] ) )
			{
				$result = $this->database->command( 'update tpl set status=1 where id = ' . $data['id'] );
			}
			return $result;
		}


		/**
		 * 根据条件判断记录是否唯一
		 * detail description
		 * @param string user
		 * @param integer id
		 * @return boolean
		 */
		function is_unique( $cate_id, $type )
		{
			$argument = load( 'biz.argument' );
			if ( $type == $argument->TP_OTHER )
			{
				return true;
			}
			$result = $this->database->unique( "select id from tpl where cate_id = " . $cate_id . " and type=" . $type . " and status=0 " );
			return isset( $result['id'] ) ? false : true;
		}

	}
?>